package com.aiti.lulian.service.newCard;

import cn.hutool.core.util.IdUtil;
import com.aiti.base.core.utils.message.Message;
import com.aiti.lulian.dto.newCard.CardPrivacySettingDto;
import com.aiti.lulian.entity.newCard.CardBaseInfo;
import com.aiti.lulian.entity.newCard.CardPrivacySetting;
import com.aiti.lulian.mapper.newCard.CardPersonalBaseInfoMapper;
import com.aiti.lulian.mapper.newCard.CardPrivacySettingMapper;
import com.aiti.lulian.service.CardPrivacySettingService;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class CardPrivacySettingServiceImpl extends ServiceImpl<CardPrivacySettingMapper, CardPrivacySetting> implements CardPrivacySettingService {

    @Autowired
    private CardPrivacySettingMapper cardPrivacySettingMapper;
    @Autowired
    private CardPersonalBaseInfoMapper cardPersonalBaseInfoMapper;

    @Override
    public Message updatePrivacySetting(CardPrivacySettingDto dto) {
        CardBaseInfo cardBaseInfo = cardPersonalBaseInfoMapper.selectById(dto.getCardId());
        if (cardBaseInfo == null) {
            return Message.fail("名片信息失效");
        }
        // 先查询下该名片的隐私设置是否已被初始化
        CardPrivacySetting isExist = cardPrivacySettingMapper.selectOne(new LambdaUpdateWrapper<CardPrivacySetting>().eq(CardPrivacySetting::getCardId, dto.getCardId()));
        if (isExist == null) {
            // 若由于链路问题尚未被初始化出来，则先将其初始化
            cardPrivacySettingMapper.insert(CardPrivacySetting.builder().baseId(IdUtil.simpleUUID()).userId(cardBaseInfo.getUserId()).cardId(cardBaseInfo.getBaseId()).baseUpdateTime(new Date()).build());
        }
        CardPrivacySetting cardPrivacySetting = new CardPrivacySetting();
        BeanUtils.copyProperties(dto, cardPrivacySetting);
        this.update(new LambdaUpdateWrapper<CardPrivacySetting>().eq(CardPrivacySetting::getCardId, dto.getCardId())
                .set(dto.getDiscoverable() != null, CardPrivacySetting::getDiscoverable, dto.getDiscoverable())
                .set(dto.getOnPopular() != null, CardPrivacySetting::getOnPopular, dto.getOnPopular())
                .set(dto.getInfoVisible() != null, CardPrivacySetting::getInfoVisible, dto.getInfoVisible())
                .set(dto.getCardShareable() != null, CardPrivacySetting::getCardShareable, dto.getCardShareable())
                .set((dto.getDiscoverable() != null || dto.getOnPopular() != null || dto.getInfoVisible() != null || dto.getCardShareable() != null), CardPrivacySetting::getBaseUpdateTime, new Date()));
        return Message.success("设置成功");
    }
}
